#include "campus_chat_manager.h"
#include "../log/campus_logger.h"

CampusChatManager::CampusChatManager(int port_):
    chat_server_(std::make_shared<CampusChatServer>(port_, this))
{
}

CampusChatManager::~CampusChatManager()
{
}

void CampusChatManager::start() 
{
    if(chat_server_->init() != 0){
        CampusLogger::warn("ChatServer init fail");
        return;
    }

    if(chat_server_->run() != 0){
        CampusLogger::warn("ChatServer run fail");
        return;
    }

    CampusLogger::info("ChatServer start success");
}

void CampusChatManager::wait()
{
    if(chat_server_->wait() != 0){
        CampusLogger::warn("ChatServer wait fail");
        return;
    }
    CampusLogger::info("CampusChatManager wait success");
}

void CampusChatManager::handleChatMsg(websocketpp::connection_hdl hdl, json JMsg)
{
    CampusLogger::info("handleChatMsg");
    std::string roomStr = JMsg["roomId"];
    int roomId = stoi(roomStr);
    std::string uid = JMsg["uid"];

    std::string msg = JMsg["msg"];
    std::string serial =  JMsg["serial"]; //序列号

    //发给自己
    json JMsg_resp;
    JMsg_resp["cmd"] = SIGNAL_TYPE_CHAT_RESP_MSG;
    JMsg_resp["serial"] = serial;
    chat_server_->send(hdl, JMsg_resp.dump());
    
    //发给房间内其他用户
    for(auto &client : room_map[roomId]){
        if(client.uid != uid){
            chat_server_->send(client.hdl, JMsg.dump()); 
        }  
    }

}

void CampusChatManager::handleChatJoin(websocketpp::connection_hdl hdl, json JMsg)
{
    // 解析JSON
    std::string uid = JMsg["uid"];
    std::string roomStr = JMsg["roomId"];
    int roomId = stoi(roomStr);

    CampusLogger::info("uid = {} try to join roomId = {}", uid, roomId);

    // 房间不存在
    if (!room_map.count(roomId))
    {
        ChatClient client = {uid, roomId, hdl};
        room_map[roomId].push_back(client);
    } 
    else //加入房间
    {
        ChatClient client = {uid, roomId, hdl};
        room_map[roomId].push_back(client);
    }
}
